package stdio.costa.moca.servlet;

import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;

import stdio.costa.moca.model.UserList;

import weibo4j.model.User;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class CallBackServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// http://myimoca.org/costa-moca/callback.xhtml?state=...&code=d8a85cd6321d87da9208d1485eecb1c0
		System.out.println("getAccessToken" + new Date());
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		System.out.println(code);
		System.out.println(state);

		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource service = client.resource(getBaseURI());

		MultivaluedMap<String, String> param = new MultivaluedMapImpl();
		param.add("code", code);
		String accessToken = service.path("authorization").path("getAccessToken").queryParams(param)
				.type(MediaType.APPLICATION_FORM_URLENCODED).post(String.class);

		if (accessToken != null) {
			List<User> usersList = service.path("/friends/getFriendsList/").path(accessToken).type(MediaType.APPLICATION_XML)
					.get(UserList.class).getUserList();

			request.setAttribute("usersList", usersList);
			request.getRequestDispatcher("/friends.jsp").forward(request, response);
		}

		else {
			response.sendRedirect("http://localhost/moca/error.xhtml");
		}
		System.out.println("------");

	}

	@Override
	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doGet(arg0, arg1);
	}

	public URI getBaseURI() {
		return UriBuilder.fromUri("http://localhost/moca/rest").build();
	}

	private static final long serialVersionUID = -8625471809840252215L;

}
